<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 读取配置数据
 *
 * @access	public
 * @param	string	
 * @return	mixed
 */
if ( ! function_exists('setting'))
{
	function setting($key)
	{
		$ci = &get_instance();
		return 	$ci->settings->item($key);
	}
}

// ------------------------------------------------------------------------

/**
 * 更新缓存
 *
 * @access	public
 * @param	array
 * @param	string
 * @return	void
 */
if ( ! function_exists('update_cache'))
{
	function update_cache($array, $fix = '')
	{
		$ci = &get_instance();
		$ci->load->model('cache_model');
		$array = is_array($array) ? $array : array($array);
		foreach ($array as $v)
		{
			$method = 'update_' . $v . '_cache';
			$ci->cache_model->$method($fix);
		}
	}
}
if ( ! function_exists('url'))
{
	function url($url){
            
            $site_url = site_url($url);
            echo $site_url;
         
	}
}

if ( ! function_exists('web_url'))
{
	function web_url($url){
            
            $site_url = site_url($url);
            return $site_url;
         
	}
}
if ( ! function_exists('front_url'))
{
	function front_url($uuid,$controller,$action){
            
            $site_url = site_url($controller."/".$uuid.($action ? "/".$action : ""));
            echo $site_url;
         
	}
}
if ( ! function_exists('web_redirect'))
{
	function web_redirect($url){
            header("Location:http://".$_SERVER['HTTP_HOST']."/".$url);exit;
	}
}

if(! function_exists('share_url')){
    function share_url($url){
        return "http://".$_SERVER['HTTP_HOST']."/".$url.".html";exit;
    }
}

//验证email地址的正确性
if ( ! function_exists('check_email'))
{
	function check_email($email)
	{
	    $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
		if (strpos($email, '@') !== false && strpos($email, '.') !== false){
			if (preg_match($chars, $email)){
				//验证通过
				return $email;
			}else{
				return false;
			}
		}else{
			return false;
		}
		
	}
}

//验证手机号的正确性
if ( ! function_exists('check_mobile'))
{
	function check_mobile($mobile)
	{
	   $strlen = strlen($mobile);
	   if($strlen!=11){
			return false;
	   }
	   if(preg_match("/^13[0-9]{1}[0-9]{8}$|147[0-9]{8}$|15[012357689]{1}[0-9]{8}$|17[0123456789]{1}[0-9]{8}$|18[0123456789]{1}[0-9]{8}$|189[0-9]{8}$/",$mobile)){    
		//验证通过
		 return $mobile;
		}else{    
			//手机号码格式不对    
			return false;
		}
	}
}
// ------------------------------------------------------------------------
/**************************************************************
 *
 *    将数组转换为JSON字符串（兼容中文）
 *    @param  array   $array      要转换的数组
 *    @return string      转换得到的json字符串
 *    @access public
 *
 *************************************************************/
function JSON($array){
	arrayRecursive($array, 'urlencode', true);
	$json = json_encode($array);
	return urldecode($json);
}

//json_encode 中文处理
/**************************************************************
	   *
	   *    使用特定function对数组中所有元素做处理
	   *    @param  string  &$array     要处理的字符串
	   *    @param  string  $function   要执行的函数
	   *    @return boolean $apply_to_keys_also     是否也应用到key上
	   *    @access public
	   *
 *************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
	static $recursive_counter = 0;
	if (++$recursive_counter > 1000) {
		die('possible deep recursion attack');
	}
	foreach ($array as $key => $value) {
		if (is_array($value)) {
			arrayRecursive($array[$key], $function, $apply_to_keys_also);
		} else {
			$array[$key] = $function($value);
		}
 
		if ($apply_to_keys_also && is_string($key)){
			$new_key = $function($key);
			if ($new_key != $key) {
				$array[$new_key] = $array[$key];
				unset($array[$key]);
			}
		}
	}
	$recursive_counter--;
} 
/**
 * 手机格式化
 * 如：18357212541 格式化成 183****2541
 */
function mobile_formart($mobile){
    if($mobile){
        return substr_replace($mobile,'****',3,4);
    }else{
        return '';
    }
}
/**
 * 邮箱格式化
 * 如：1638025412@qq.com 格式化成 163***12@qq.com
 */
function email_formart($email){
    if(strpos($email,"@")){
        //查找“@”的位置
        $pos = strpos($email,"@");
        $end_str = substr($email, $pos-1);
        $start_str = substr($email, 0,3);
        return $start_str.'****'.$end_str;
    }else{
        return '';
    }
}

/**
 * 用户名格式化
 * 如：1638025412@qq.com 格式化成 163***12@qq.com
 */
function name_formart($name){
    if($name){
        $start = mb_substr($name, 0, 2, 'utf-8');
        $end = mb_substr($name, -2, 2, 'utf-8');
        return $start.'***'.$end;
    }else{
        return '';
    }
}
/**
 * 用户昵称格式化
 * 如：大主宰 格式化成 大****宰
 */
function nick_formart($name){
    if($name){
        $start = mb_substr($name,0,1,'utf8');
        $end = mb_substr($name,-1,1,'utf8');
        return $start.'**'.$end;
    }else{
        return '';
    }
}
/**
 * 根据用户所投金额匹配所得体验积分值
 * @param type $exper
 * @param type $amount
 */
function match_exper($exper = array(),$amount){
    if($amount){
        foreach ($exper as $key => $val) {
            if($amount >= $val['min'] && $amount <= $val['max']){
                return $val['exper'];
            }
        }
    }
}

//打印函数
function p($arr){
	echo "<pre>";
	print_r($arr);
	echo "</pre>";
}

//生成订单号OrdId
if ( ! function_exists('MakeOrdId'))
{
    function MakeOrdId($user_id) {
        $nid = $user_id+1000000;
        $OrdId = $nid.date('ymdHis').rand(0,9); //20位交易流水号（唯一）
        return $OrdId;
        
    }	
}

/**
 * 构造站内信通知模板
 * @param type $tpl 站内信通知模板
 * @param type $content 站内信内容
 * @return type
 */
function mail_notice_tpl($tpl,$content){
    return str_replace("[content]", $content,$tpl);
}
/**
 * 将二维数组转换为一维数组
 * @param type $array2
 */
function array2_to_array1($array2,$colum_key){
    $temp = array();
    foreach ($array2 as $key=>$val){
        $temp[] = $val[$colum_key];
    }
    return $temp;
}
/**
 * 随机返回指定数量的值
 * @param type $arr
 * @param type $num
 */
function array_rand_value($arr,$num){
    $arr_key = array_rand($arr, $num);
    $result = array();
    foreach ($arr_key as $key=>$val){
        $result[] = $arr[$val];
    }
    return $result;
}
/**
 * 匹配评论表情图片
 * @param type $str
 * @return type
 */
function gifreplace($str){
    $str = str_replace(">",'<；',$str); 
    $str = str_replace(">",'>；',$str); 
    $str = str_replace("\n",'>；br/>；',$str); 
    $str = preg_replace("[\[em_([0-9]*)\]]","<img src=\"http://static.tan66.com/upfiles/face/$1.gif\" />",$str); 
    return $str; 
}

function _getcookie($name){
	if(empty($name)){return false;}
	if(isset($_COOKIE[$name])){
		return $_COOKIE[$name];
	}else{		
		return false;
	}
}

function _setcookie($name,$value,$time=0,$path='/',$domain=''){		
	if(empty($name)){return false;}
	$_COOKIE[$name]=$value;				//及时生效
	$s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
	if(!$time){
		return setcookie($name,$value,0,$path,$domain,$s);
	}else{
		return setcookie($name,$value,time()+$time,$path,$domain,$s);
	}
}

//生成夺宝订单号
function pay_get_dingdan_code($dingdanzhui=''){
    return $dingdanzhui.time().substr(microtime(),2,6).rand(0,9);
}

/*HTML安全过滤*/
function _htmtocode($content) {
    $content = str_replace('%','%&lrm;',$content);
    $content = str_replace("<", "&lt;", $content);
    $content = str_replace(">", "&gt;", $content);            
    $content = str_replace("\n", "<br/>", $content);
    $content = str_replace(" ", "&nbsp;", $content);
    $content = str_replace('"', "&quot;", $content);
    $content = str_replace("'", "&#039;", $content);
    $content = str_replace("$", "&#36;", $content);
    $content = str_replace('}','&rlm;}',$content);
    return $content;
}

/* 网络操作函数 */
function _g_triggerRequest($url,$io=false,$post_data = array(), $cookie = array()){
    $method = empty($post_data) ? 'GET' : 'POST';
    $url_array = parse_url($url);		
    $port = isset($url_array['port'])? $url_array['port'] : 80; 
    if(function_exists('fsockopen')){
        $fp = @fsockopen($url_array['host'], $port, $errno, $errstr, 30);
    }elseif(function_exists('pfsockopen')){
        $fp = @pfsockopen($url_array['host'], $port, $errno, $errstr, 30);
    }elseif(function_exists('stream_socket_client')){
        $fp = @stream_socket_client($url_array['host'].':'.$port,$errno,$errstr,30);
    } else {
        $fp = false;
    }
    if(!$fp){
        return false;
    }		

    $url_array['query'] =  isset($url_array['query']) ? $url_array['query'] : '';		
    $getPath = $url_array['path'] ."?". $url_array['query'];

    $header  = $method . " " . $getPath." ";
    $header .= "HTTP/1.1\r\n";
    $header .= "Host: ".$url_array['host']."\r\n"; //HTTP 1.1 Host域不能省略
    $header .= "Pragma: no-cache\r\n";

    if(!empty($cookie)){
    $_cookie_s = strval(NULL);
    foreach($cookie as $k => $v){
        $_cookie_s .= $k."=".$v."; ";
    }
    $_cookie_s = rtrim($_cookie_s,"; ");
    $cookie_str =  "Cookie: " . base64_encode($_cookie_s) ." \r\n";	   //传递Cookie
    $header .= $cookie_str;
    }
            $post_str = '';
    if(!empty($post_data)){
        $_post = strval(NULL);
        foreach($post_data as $k => $v){
            $_post .= $k."=".urlencode($v)."&";
        }
        $_post = rtrim($_post,"&");
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";//POST数据
        $header .= "Content-Length: ". strlen($_post) ." \r\n";//POST数据的长度	

        $post_str = $_post."\r\n"; //传递POST数据
    }
    $header .= "Connection: Close\r\n\r\n";
    $header .= $post_str;

    fwrite($fp,$header);
    if($io){		
        while (!feof($fp)){ 
            echo fgets($fp,1024);
        }
    }   
    fclose($fp);
    return true;
}

//系统提醒
function _message($string=null,$defurl=null,$time=2,$config=null){
    
    if(empty($defurl)){
        $defurl = ":js:";	
    }
    if(empty($config)){
            $config = array("titlebg"=>"#549bd9","title"=>"#fff");
    }		
    $str_url_two = array("url" => web_url("lottery"),"text" => "返回夺宝首页");
    $time = intval($time);
    if($time < 2){ $time = 2;}
    
    $html = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
    $html .= "<html xmlns='http://www.w3.org/1999/xhtml' >";
    $html .= "<head>";
    $html .= "   <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";
    $html .= "   <title>".$string."</title>";
    $html .= "   <meta name='robots' content='noindex, nofollow' />";
    $html .= "   <style type='text/css'>";
    $html .= "   *{margin:0;padding:0;}";
    $html .= "   html,body{ overflow:hidden}";
    $html .= "   body{color:#333;font:12px/1.5 Tahoma,Arial,'宋体',Helvetica,sans-serif;height:auto;width:100%; background-color:#f9f9f9}";
    $html .= "   div{margin:0 auto;}";
    $html .= "   ul{list-style-type:none;}";
    $html .= "   .box{ border:5px solid #eee; width:480px; background-color:#fff;margin-top:15%;erflow:hidden;}";
    $html .= "   .box-b{ border:1px solid #dfdbdb;width:478px;erflow:hidden;}";
    $html .= "   .box-title{ background:".(isset($config['titlebg']) ? $config['titlebg'] : "#f60").";height:30px;line-height:33px;_line-height:30px;font-size: 14px;color:".(isset($config['title']) ? $config['title'] : "#fff")."; padding:0 10px;}";
    $html .= "   .box-text{font:12px/1.5 '微软雅黑',Arial,'宋体',Helvetica,sans-serif; font-size:18px;color:#73787b;width:438px;text-align:center; border:0px solid #000; padding:20px; height:auto;word-wrap:break-word;}";
    $html .= "   .box-button{overflow:hidden; text-align:right;}";
    $html .= "   .box-button a{display: inline-block;height:25px;line-height:23px;_line-height:25px;text-align: center;font-family:'微软雅黑';font-size: 14px;text-decoration: none;padding:0px 5px;margin:0px 10px;}";
    $html .= "   .a-1{ background-color:#eee; color:#666; border:1px solid #dfdbdb;}";
    $html .= "   .a-2{ background-color:#eee; color:#666;border:1px solid #dfdbdb;}";
    $html .= "   </style>";
    $html .= "   <script>";
    $html .= "        function goback(){";
    $html .= "         if('".$defurl."' == ':js:'){window.history.back();}else{location.href='".$defurl."';}";
    $html .= "        }";
    $html .= "        function closeWindow(){window.open('', '_self', '');window.close();}";
    $html .= "        var i = ".$time.";";
    $html .= "        if(i!=0){";
    $html .= "            window.close_id = setInterval(function() {if (i > 0){document.getElementById('time').innerHTML = i;i = i - 1;} else {goback();clearInterval(window.close_id);}}, 1000);";
    $html .= "        }";
    $html .= "   </script>";
    $html .= "</head>";
    $html .= "<body>";
    $html .= "   <div class='box'>";
    $html .= "      <div class='box-b'>";
    $html .= "          <div class='box-title'>消息提示</div>";
    $html .= "          <div class='box-text'>".$string."</div>";
    $html .= "          <div class='box-button'><a class='a-2' href='javascript:;' onclick='goback();'><font id='time' style='color:red;'>".$time."</font>秒后返回上一页面</a><a class='a-1' href='".$str_url_two['url']."'>".$str_url_two['text']."</a></div> ";
    $html .= "          <div style='height:10px; overflow:hidden; width:100%; clear:both'></div>";
    $html .= "      </div>";
    $html .= "   </div>";
    $html .= "</body>";
    $html .= "</html>";
    
    echo $html;exit;
}

function microt($time,$x=null){
    $len=strlen($time);
    if($len<13){
        $time=$time."0";
    }
    $list=explode(".",$time);	
    if($x=="L"){		
        return date("His",$list[0]).substr($list[1],0,3);
    }else if($x=="Y"){
        return date("Y-m-d",$list[0]);
    }else if($x=="H"){
        return date("H:i:s",$list[0]).".".substr($list[1],0,3);
    }else if($x=="r"){
        return date("Y年m月d日 H:i",$list[0]);
    }else if($x=="s"){
        return date("Y/m/d H:i",$list[0]);
    }else{
        return date("Y-m-d H:i:s",$list[0]).".".substr($list[1],0,3);
    }
}
/*字符过滤url*/
function safe_replace($string) {
    $string = str_replace('%20','',$string);
    $string = str_replace('%27','',$string);
    $string = str_replace('%2527','',$string);
    $string = str_replace('*','',$string);
    $string = str_replace('"','&quot;',$string);
    $string = str_replace("'",'',$string);
    $string = str_replace('"','',$string);
    $string = str_replace(';','',$string);
    $string = str_replace('<','&lt;',$string);
    $string = str_replace('>','&gt;',$string);
    $string = str_replace("{",'',$string);
    $string = str_replace('}','',$string);
    $string = str_replace('\\','',$string);		
    return $string;
}

function host_url(){
    return "http://".$_SERVER['HTTP_HOST'];
}


if ( ! function_exists('finance_url'))
{
	function finance_url($url){
            $site_url = "http://finance.tan2.com/".($url ? $url.".html" : "");
            echo $site_url;
	}
}

if ( ! function_exists('finance_base_url'))
{
	function finance_base_url($url){
            $site_url = "http://finance.tan2.com/".($url ? $url.".html" : "");
            return $site_url;
	}
}

if ( ! function_exists('finance_redirect_url'))
{
	function finance_redirect_url($url){
            $site_url = "http://finance.tan2.com".$url;
            header("Location:".$site_url);exit;
	}
}